package com.sqx.modules.sysUserAddress.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.sqx.modules.sysUserAddress.dao.SysUserAddressDao;
import com.sqx.modules.sysUserAddress.entity.SysUserAddress;
import com.sqx.modules.sysUserAddress.service.ISysUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wuChang
 * @since 2023-08-10
 */
@Service
public class SysUserAddressServiceImpl extends ServiceImpl<SysUserAddressDao, SysUserAddress> implements ISysUserAddressService {

    @Autowired
    private CityInfoService cityInfoService;

    @Override
    public Result saveAddress(SysUserAddress sysUserAddress) {
        if (sysUserAddress.getIsDefault() != null && sysUserAddress.getIsDefault() == 1) {
            SysUserAddress address = new SysUserAddress();
            address.setIsDefault(0);
            baseMapper.update(address, new QueryWrapper<SysUserAddress>().eq("user_id", sysUserAddress.getUserId()));
        } else {
            sysUserAddress.setIsDefault(0);
        }

        if (sysUserAddress.getAddressId() != null) {
            sysUserAddress.setUpdateTime(LocalDateTime.now());
            return Result.upStatus(baseMapper.updateById(sysUserAddress));
        } else {
            sysUserAddress.setCreateTime(LocalDateTime.now());
            sysUserAddress.setUpdateTime(LocalDateTime.now());
            return Result.upStatus(baseMapper.insert(sysUserAddress));
        }
    }

    @Override
    public IPage<SysUserAddress> getAddressList(Integer page, Integer limit, SysUserAddress sysUserAddress) {
        Page<SysUserAddress> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<SysUserAddress> userAddressIPage = baseMapper.selectPage(pages, new QueryWrapper<>(sysUserAddress).orderByDesc("create_time"));
        for (SysUserAddress record : userAddressIPage.getRecords()) {
            record.setCityIsOpen(cityInfoService.isOpenCity(record.getCity()));
        }
        return userAddressIPage;

    }
}
